<?php

namespace app\admin\model\chase;

use app\api\model\Wechat;
use think\Model;


class PromotionCode extends Model
{

    

    

    // 表名
    protected $table = 'promotion_code';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
    
    /**
     * 创建小程序码
     */
    public static function createCode($merchant_id)
    {
        //生成小程序码
        $dir = ROOT_PATH . 'public/uploads/promotion/';
        $data = [
            'scene' => 'merchant_id='.$merchant_id,
        ];
        $filePath = $dir . md5($data['scene']) . '.png';
        //获取小程序码
        $wechat = new Wechat();
        $res = $wechat->getORCode($data);
        if (isset($res['errcode'])) {
            return ['errcode' => $res['errcode'], 'errmsg' => $res['errmsg']];
        }
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        //将二进制小程序码转换为图片保存
//        $file = fopen($filePath, 'w');
//        fwrite($file, $res);
//        fclose($file);
        file_put_contents($filePath, $res);
        $image = str_replace(ROOT_PATH . 'public', '', $filePath);
        return $image;
    }

    public static function getByMerchant($merchant_id)
    {
        return self::where('merchant_id', $merchant_id)->find();
    }





}
